package com.huhu.sys.shiro;

import com.huhu.entity.User;
import com.huhu.service.UserService;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by xuyi on 2016/9/13.
 */
@Service
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private CredentialsMatcher credentialsMatcher;
    /**
     * 权限认证
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String loginName = (String) principalCollection.fromRealm(getName()).iterator().next();
        User user = userService.findByName(loginName);
        if (user != null) {
            //权限信息对象，存储角色与权限的
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //获得User的详细
            User userRoles = userService.findURoleAndPer(user);

            //设置用户的角色集合
            info.setRoles(userRoles.getAllRole());
            //用户的角色对应的所有权限
            info.setStringPermissions(userRoles.getAllPermission());
            return info;
        }
        return null;
    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByName(token.getUsername());

        //将此用户放到登录认证Info中
        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt() + "huhuxs"));

        boolean flag = credentialsMatcher.doCredentialsMatch(authenticationToken, authenticationInfo);
        if (flag) {
            token.setPassword(user.getPassword().toCharArray());
            return authenticationInfo;
        } else {
            return authenticationInfo;
        }
    }

}
